package com.hunliji.monitor.web.strategy.inform;

import com.alibaba.fastjson.JSON;
import com.hunliji.monitor.manager.api.FeiShuManager;
import com.hunliji.monitor.manager.api.model.dto.FeiShuSendMsgDTO;
import com.hunliji.monitor.manager.api.model.param.FeiShuSendMsgManagerParam;
import com.hunliji.monitor.service.api.InformActionStrategyService;
import com.hunliji.monitor.service.api.UserInfoService;
import com.hunliji.monitor.service.api.model.bo.InformActionStrategyBO;
import com.hunliji.monitor.service.api.model.bo.UserInfoBO;
import com.hunliji.monitor.service.api.model.param.QueryInformActionStrategyParam;
import com.hunliji.monitor.share.enums.ReceiveIdTypeEnum;
import com.hunliji.monitor.share.enums.SeverityEnum;
import com.hunliji.monitor.web.facade.FeiShuFacade;
import com.hunliji.monitor.web.strategy.inform.model.InformDescription;
import com.hunliji.monitor.web.strategy.inform.model.InformTouching;
import com.hunliji.monitor.web.strategy.inform.model.feishu.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 飞书群通知处理器
 * @author wuchen
 */
@Service
public class FeiShuChatInformAction extends AbstractInformAction {
    private static final Logger logger = LoggerFactory.getLogger(FeiShuChatInformAction.class);
    @Resource
    private FeiShuManager feiShuManager;
    @Resource
    private FeiShuFacade feiShuFacade;
    @Resource
    private InformActionStrategyService informActionStrategyService;
    @Resource
    private UserInfoService userInfoService;

    /**
     * 飞书的消息的常量
     */
    class FeiShuMessageConstants{
        /**
         * tag 类型 -plain_text
         */
        private static final String PLAIN_TEXT_TAG =  "plain_text";
        /**
         * tag 类型 -div
         */
        private static final String DIV_TAG = "div";
        /**
         * tag 类型 -lark_md
         */
        private static final String LARK_MD_TAG = "lark_md";
        /**
         * tag 类型 -hr - 就是分割线
         */
        private static final String HR_TAG = "hr";

        /**
         * 标题主题色-绿
         */
        private static final String TEMPLATE_GREEN = "green";

        /**
         * 标题主题色-蓝
         */
        private static final String TEMPLATE_BLUE = "blue";
        /**
         * 标题主题色-橙色
         */
        private static final String TEMPLATE_ORANGE = "orange";

        /**
         * 标题主题色-红
         */
        private static final String TEMPLATE_RED = "red";

        /**
         * 标题主题色-紫
         */
        private static final String TEMPLATE_VIOLET = "violet";


    }
    /**
     * 通知
     * @param touching：触达
     * @param description：描述
     */
    @Override
    public void inform(InformTouching touching, InformDescription description) {
        FeiShuInformContainer feiShuInformContainer = getContainer(touching,description);
        FeiShuInformMessage feiShuInformMessage = new FeiShuInformMessage();
        feiShuInformMessage.setContent(JSON.toJSONString(feiShuInformContainer));
        //构建发送飞书消息的结构
        FeiShuSendMsgManagerParam param = FeiShuSendMsgManagerParam.builder()
                .receiveIdType(ReceiveIdTypeEnum.CHAT_ID.getCode())
                .receiveId(touching.getPlatformId())
                .msgType("interactive").build();
        param.setContent(JSON.toJSONString(feiShuInformContainer));
        try {
            String accessToken = feiShuFacade.getAccessToken();
            FeiShuSendMsgDTO feiShuSendMsgDTO = feiShuManager.sendMsg(param,accessToken);
            if(Objects.nonNull(feiShuSendMsgDTO)){
                urgentApp(touching,feiShuSendMsgDTO.getMessageId());
            }
        }catch (Exception e){
            logger.warn("inform to fei shu chat error,param:{}",param,e);
        }
    }

    @Override
    public void informToUser(String userId, InformDescription description) {
        FeiShuInformContainer feiShuInformContainer = getContainerOfChangeOrder(description);
        FeiShuInformMessage feiShuInformMessage = new FeiShuInformMessage();
        feiShuInformMessage.setContent(JSON.toJSONString(feiShuInformContainer));
        //构建发送飞书消息的结构
        FeiShuSendMsgManagerParam param = FeiShuSendMsgManagerParam.builder()
                .receiveIdType(ReceiveIdTypeEnum.USER_ID.getCode())
                .receiveId(userId)
                .msgType("interactive").build();
        param.setContent(JSON.toJSONString(feiShuInformContainer));
        try {
            String accessToken = feiShuFacade.getAccessToken();
            FeiShuSendMsgDTO feiShuSendMsgDTO = feiShuManager.sendMsg(param,accessToken);
        }catch (Exception e){
            logger.warn("inform to fei shu chat error,param:{}",param,e);
        }
    }

    /**
     * 加急
     * todo 目前只有在严重状态下会进行加急
     * @param touching
     * @param messageId
     */
    private void urgentApp(InformTouching touching,String messageId){
        //如果当前状态为严重，则需要进行加急操作
        if(SeverityEnum.SERIOUS.getCode().equals(touching.getSeverity())){
            List<String> feiShuUserIdList = getFeiShuUserIdList(touching.getInformActionStrategyBOList());
            String accessToken = feiShuFacade.getAccessToken();
            feiShuManager.urgentPhone(feiShuUserIdList,messageId,accessToken);
        }
    }


    /**
     * 构建飞书通知容器
     * @param touching
     * @param description
     * @return
     */
    private FeiShuInformContainer getContainer(InformTouching touching,InformDescription description){
        FeiShuInformContainer feiShuInformContainer = new FeiShuInformContainer();
        List<FeiShuInformElements> elements = new ArrayList<>();

        //核心描述信息，就是一句话表达是什么问题
        FeiShuInformElements descElement = new FeiShuInformElements();
        descElement.setTag(FeiShuMessageConstants.DIV_TAG);
        descElement.setFields(Arrays.asList(buildField("指标描述",description.getMsg())));
        elements.add(descElement);

        //其他描述信息
        if(!CollectionUtils.isEmpty(description.getExtra())){
            //分割线
            elements.add(buildSplitLine());
            description.getExtra().forEach((key,item)->{
                FeiShuInformElements extraElement = new FeiShuInformElements();
                extraElement.setTag(FeiShuMessageConstants.DIV_TAG);
                extraElement.setFields(Arrays.asList(buildField(key,item)));
                elements.add(extraElement);
            });
        }
        //分割线
        elements.add(buildSplitLine());
        //at信息
        elements.add(buildAtFeiShuInformElements(touching));
        //操作

        feiShuInformContainer.setHeader(buildHeader(touching,description));
        feiShuInformContainer.setElements(elements);
        return feiShuInformContainer;

    }


    /**
     * 构建飞书通知容器
     * @param description
     * @return
     */
    private FeiShuInformContainer getContainerOfChangeOrder(InformDescription description){
        FeiShuInformContainer feiShuInformContainer = new FeiShuInformContainer();
        List<FeiShuInformElements> elements = new ArrayList<>();

        //核心描述信息，就是一句话表达是什么问题
        FeiShuInformElements descElement = new FeiShuInformElements();
        descElement.setTag(FeiShuMessageConstants.DIV_TAG);
        descElement.setFields(Arrays.asList(buildField("变更单通知内容",description.getMsg())));
        elements.add(descElement);

        //其他描述信息
        if(!CollectionUtils.isEmpty(description.getExtra())){
            //分割线
            elements.add(buildSplitLine());
            description.getExtra().forEach((key,item)->{
                FeiShuInformElements extraElement = new FeiShuInformElements();
                extraElement.setTag(FeiShuMessageConstants.DIV_TAG);
                extraElement.setFields(Arrays.asList(buildField(key,item)));
                elements.add(extraElement);
            });
        }
//        //分割线
//        elements.add(buildSplitLine());
//        //at信息
//        elements.add(buildAtFeiShuInformElements(touching));
        //操作

        feiShuInformContainer.setHeader(buildHeader(null,description));
        feiShuInformContainer.setElements(elements);
        return feiShuInformContainer;

    }



    /**
     * 设置严重程度对应的主题设置
     * @param header
     * @param severity
     */
    private void setTemplate(FeiShuInformHeader header,Integer severity){
        if(SeverityEnum.ONLY_REPORT.getCode().equals(severity)){
            //如果是报告类型
            header.setTemplate(FeiShuMessageConstants.TEMPLATE_GREEN);
        }else if(SeverityEnum.LOW.getCode().equals(severity)){
            //如果是低等级的
            header.setTemplate(FeiShuMessageConstants.TEMPLATE_BLUE);
        }else if(SeverityEnum.MEDIUM.getCode().equals(severity)){
            //如果是中等级的
            header.setTemplate(FeiShuMessageConstants.TEMPLATE_ORANGE);
        }else if(SeverityEnum.HIGH.getCode().equals(severity)){
            //如果是高等级的
            header.setTemplate(FeiShuMessageConstants.TEMPLATE_RED);
        }else if(SeverityEnum.SERIOUS.getCode().equals(severity)){
            //如果是严重
            header.setTemplate(FeiShuMessageConstants.TEMPLATE_VIOLET);
        }else {
            //默认的为报告类型
            header.setTemplate(FeiShuMessageConstants.TEMPLATE_GREEN);
        }

    }

    private FeiShuInformField buildField(String descTitle,String desc){
        FeiShuInformField descField = new FeiShuInformField();
        descField.setIsShort(false);
        FeiShuInformContent content = new FeiShuInformContent();
        content.setTag(FeiShuMessageConstants.LARK_MD_TAG);
        content.setContent(descTitle + ":" + desc);
        content.setLines(5);
        descField.setText(content);
        return descField;
    }

    private FeiShuInformElements buildSplitLine(){
        FeiShuInformElements elements = new FeiShuInformElements();
        elements.setTag(FeiShuMessageConstants.HR_TAG);
        return elements;
    }

    private FeiShuInformHeader buildHeader(InformTouching touching,InformDescription description){
        //构建头信息，构建标题
        FeiShuInformHeader header = new FeiShuInformHeader();
        if(Objects.nonNull(touching)){
            //设置严重程度
            setTemplate(header,touching.getSeverity());
            //设置标题
            setTitle(header,touching.getSeverity(),description.getTitle());
        }else {
            setTitle(header,null,description.getTitle());
        }

        return header;
    }

    /**
     * 设置标题
     * @param header
     * @param severity
     * @param title
     */
    public void setTitle(FeiShuInformHeader header,Integer severity,String title){
        FeiShuInformContent headerContent = new FeiShuInformContent();
        headerContent.setTag(FeiShuMessageConstants.PLAIN_TEXT_TAG);
        SeverityEnum severityEnum = SeverityEnum.getByCode(severity);
        //如果是严重的状态，标题需要加强
        if(SeverityEnum.SERIOUS.getCode().equals(severity)){
            title = severityEnum.getMsg() + "    "+title ;
        }
        headerContent.setContent(title);
        header.setTitle(headerContent);
    }




    /**
     * 构建飞书的at信息
     * @param touching
     * @return
     */
    private FeiShuInformElements buildAtFeiShuInformElements(InformTouching touching){
        FeiShuInformElements atElement = new FeiShuInformElements();
        atElement.setTag(FeiShuMessageConstants.DIV_TAG);
        List<Long> userIdList = new ArrayList<>();
        List<InformActionStrategyBO> informActionStrategyBOList = touching.getInformActionStrategyBOList();
        if(!CollectionUtils.isEmpty(informActionStrategyBOList)){
            userIdList = informActionStrategyBOList.stream().map(InformActionStrategyBO::getUserId).collect(Collectors.toList());
        }
        List<UserInfoBO> atUsersBOList = userInfoService.getListByIds(userIdList);
        List<String> atUserIdList = atUsersBOList.stream().map(UserInfoBO::takeFeishuUserId).collect(Collectors.toList());
        atElement.setFields(Arrays.asList(buildField("关注人",buildAt(atUserIdList))));

        return atElement;
    }

    private String buildAt(List<String> userIdList){
        StringBuffer sb = new StringBuffer("");
        for (String userId:userIdList){
            sb.append("<at id=");
            sb.append(userId);
            sb.append("></at>");
        }
        return sb.toString();
    }

    /**
     * 根据策略获取飞书的用户id
     * @param informActionStrategyBOList
     * @return
     */
    private  List<String> getFeiShuUserIdList(List<InformActionStrategyBO> informActionStrategyBOList){
        List<Long> userIdList = new ArrayList<>();
        if(!CollectionUtils.isEmpty(informActionStrategyBOList)){
            userIdList = informActionStrategyBOList.stream().map(InformActionStrategyBO::getUserId).collect(Collectors.toList());
        }
        List<UserInfoBO> atUsersBOList = userInfoService.getListByIds(userIdList);
        List<String> atUserIdList = atUsersBOList.stream().map(UserInfoBO::takeFeishuUserId).collect(Collectors.toList());
        return atUserIdList;
    }




}
